<?php
/**
 * Created by PhpStorm.
 * User: zhd
 * Date: 2019/3/14
 * Time: 20:58
 */

namespace app\Module\Index\Controller;


use app\Module\Index\Logic\MessageLogic;
use app\Module\Index\Logic\MessageType;
use app\Module\Index\Model\ArticleModel;
use app\Module\Index\Model\CommentModel;
use app\Module\Index\Model\ReplyModel;
use app\Module\Index\Model\UnreadCommentModel;
use app\Module\Index\Model\UserModel;

class CommentController extends CheckAuth
{
    /**
     * 添加评论
     * @verify int      $article_id
     * @verify string   $content
     */
    public function addAction($article_id, $content)
    {
        $userModel = new UserModel();
        $data      = $userModel->row([
            'id' => session('userId'),
        ]);
        if (strtotime($data['black_time']) > time()) {
            return fail('由于您最近有违规记录，管理员已对您限制评价，时间持续至' . $data['black_time']);
        }

        // 新增评论
        $comment = new CommentModel();
        $id      = $comment->insert([
            'article_id' => $article_id,
            'content'    => $content,
            'user_id'    => session('userId'),
            'created'    => now(),
        ]);


        $article = new ArticleModel();
        $article->update('comment_num=comment_num+1', ['id' => $article_id]);

        // 新增未读
        $data = $article->row(['id' => $article_id]);
        if (session('userId') != $data['user_id']) {
            $unreadCommentModel = new UnreadCommentModel();
            $unreadCommentModel->addSet([
                'updated'         => now(),
                'last_comment_id' => $id,
            ]);
            $result = $unreadCommentModel->update('num=num+1', [
                'user_id'        => session('userId'),
                'target_user_id' => $data['user_id'],
                'article_id'     => $article_id,
            ]);
            if (empty($result)) {
                $unreadCommentModel->insert([
                    'target_user_id'  => $data['user_id'],
                    'last_comment_id' => $id,
                    'user_id'         => session('userId'),
                    'created'         => now(),
                    'updated'         => now(),
                    'num'             => 1,
                    'article_id'      => $article_id,
                ]);
            }
        }


        if ($id) {
            $messageLogic = new MessageLogic();
            $messageLogic->add($this->userId, $data['user_id'], $article_id, MessageType::ARTICLE_COMMENT, $data['content']);

            return success();
        } else {
            return fail('评论失败');
        }
    }

    /**
     * @verify int $article_id
     * @verify int $page
     * @verify int $limit
     */
    public function getListAction($article_id, $page = 1, $limit = 20)
    {
        $comment = new CommentModel();
        $comment->addWhere([
            'article_id' => $article_id,
        ]);
        $count = $comment->count();


        $comment->setFields([
            'comment.id,user_id,user.username,user.avatar_url,comment.created,comment.content',
        ]);
        $comment->setJoin('user', 'user.id = comment.user_id', 'LEFT JOIN');
        $comment->addWhere([
            'article_id' => $article_id,
        ]);
        $comment->setPage($page, $limit);
        $comment->addOrder('comment.created', false);
        $data = $comment->select();

        $reply = new ReplyModel();
        foreach ($data as $key => $datum) {
            $reply->addWhere([
                'comment_id' => $datum['id'],
            ]);
            $replyCount = $reply->count();

            $reply->setFields([
                'user_id,target_user_id,target_user.username as target_user_username,user.username,reply.content,reply.created',
            ]);
            $reply->addWhere([
                'comment_id' => $datum['id'],
            ]);
            $reply->setJoin('user', 'user.id = reply.user_id', 'LEFT JOIN');
            $reply->setJoin('user as target_user', 'target_user.id = reply.target_user_id', 'LEFT JOIN');
            $reply->addOrder('reply.created', true);
            $list                     = $reply->select();
            $data[$key]['reply']      = $list;
            $data[$key]['replyCount'] = $replyCount;
        }

        return success(['count' => $count, 'data' => $data]);
    }

    /**
     * 更新未读信息
     *
     * @verify int $user_id
     * @verify int $article_id
     * @return string
     */
    public function updateUnreadAction($user_id, $article_id)
    {
        // 更新消息为已读
        $unreadCommentModel = new UnreadCommentModel();
        $unreadCommentModel->addWhere('num', '0', '>');
        $unreadCommentModel->update(
            [
                'num'     => 0,
                'updated' => now(),
            ],
            [
                'user_id'        => $user_id,
                'article_id'     => $article_id,
                'target_user_id' => session('userId'),
            ]);

        return success();
    }

    /**
     * 获取未读评论
     *
     * @verify int|null $page
     * @verify int|null $limit
     * @return string
     */
    public function getUnreadAction($page = 1, $limit = 20)
    {
        $unreadCommentModel = new UnreadCommentModel();
        $unreadCommentModel->setFields('user.username,user.avatar_url,unread_comment.num,unread_comment.id,comment.content,comment.created,comment.id as comment_id,unread_comment.article_id');
        $unreadCommentModel->addWhere([
            'target_user_id' => session('userId'),
        ]);

        $unreadCommentModel->setJoin('comment', 'comment.id=unread_comment.last_comment_id');
        $unreadCommentModel->setJoin('user', 'user.id=comment.user_id');
        $unreadCommentModel->addOrder('comment.created', false);
        $unreadCommentModel->setPage($page, $limit);
        $data = $unreadCommentModel->select();

        return success($data);
    }
}